package com.wondersgroup.insurance.datalibrary;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/6/7.
 */

public class DateDefault0Adapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
    String dateFormat;

    public DateDefault0Adapter(String dateFormat) {
        this.dateFormat = dateFormat;
    }

    @Override
    public Date deserialize(JsonElement json, Type typeOfT,
                            JsonDeserializationContext context)
            throws JsonParseException {
        try {
            if (json.getAsString() == null || json.getAsString().equals("")){
                return null;
            }
        } catch (Exception ignore){
        }
        try {
            return getDate(json.getAsString());
        } catch (NumberFormatException e) {
            throw new JsonSyntaxException(e);
        }
    }




    @Override
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        return   new JsonPrimitive(getSystemDate(src));
    }

    public  Date getDate(String time){
        Date date = null;
        SimpleDateFormat ft = new SimpleDateFormat(dateFormat);
        try {
            date = ft.parse( time );
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date;
    }

    public  String getSystemDate(Date date){
        SimpleDateFormat ft = new SimpleDateFormat(dateFormat);
        return ft.format(date);
    }
}
